<template>
  <div class="cyber-container">
    <div class="cyber-card">
      <div class="card-header">
        <h2>我的账单</h2>
      </div>

      <div class="cyber-form-card">
        <el-form :model="searchObj" label-width="100px" class="search-form">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="房间费用">
                <el-input v-model="searchObj.room_fee" placeholder="请输入房间费用" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="额外费用">
                <el-input v-model="searchObj.extra_fee" placeholder="请输入额外费用" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="账单时间">
                <el-date-picker
                  v-model="searchObj.bill_time"
                  type="date"
                  placeholder="请选择账单时间"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" class="form-actions">
              <el-button type="primary" @click="search" class="cyber-button">
                <el-icon><Search /></el-icon>
                查询
              </el-button>
              <el-button @click="resetSearch" class="cyber-button">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="cyber-table-card">
        <el-table :data="tableData" style="width: 100%" border>
<!--          <el-table-column prop="staff_id" label="用户ID" />-->
          <el-table-column prop="staffName" label="员工姓名" />
          <el-table-column prop="room_fee" label="房间费用" />
          <el-table-column prop="extra_fee" label="额外费用" />
          <el-table-column prop="bill_time" label="账单时间" />
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="searchObj.current"
            v-model:page-size="searchObj.limit"
            :page-sizes="[10, 20, 50, 100]"
            :total="Number(total)"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 添加固定定位的联系电话信息 -->
    <div class="contact-info-fixed">
      联系电话13465134662
    </div>
  </div>
</template>

<script setup>
import api from '../api/billapi.js'
import loginApi from '../api/login_api.js'
import staffApi from '../api/staffapi.js'
import {ref, onMounted} from "vue";
import {ElMessage} from "element-plus";

//定义绑定的数据
//表格中的数据
const tableData = ref([]);

const total=ref(0);
//查询数据
const searchObj = ref({
  current: 1,
  limit: 10,
  name: '', // 将根据登录用户ID自动填充
  room_fee: '',
  extra_fee: '',
  bill_time:'',
});

// 当前登录用户信息
const currentUser = ref({});

// 员工信息映射
const staffMap = ref({});

// 获取员工信息
const loadStaffData = async () => {
  try {
    const params = {
      current: 1,
      limit: 1000 // 获取足够多的员工数据
    };
    const result = await staffApi.page(params);
    if (result && result.data) {
      // 构建员工ID到姓名的映射
      staffMap.value = {};
      result.data.forEach(staff => {
        staffMap.value[staff.id] = staff.name;
      });
    }
  } catch (error) {
    console.error("获取员工信息失败:", error);
    ElMessage.error("获取员工信息失败");
  }
};

// 获取当前登录用户信息
const getCurrentUser = async () => {
  try {
    const res = await loginApi.logininfo();
    currentUser.value = res;
    // 设置查询条件中的用户ID为当前登录用户ID
    searchObj.value.staff_id = res.id;
    return res;
  } catch (error) {
    console.error("获取用户信息失败:", error);
    ElMessage.error("获取用户信息失败");
  }
};

const search = async () => {
  try {
    // 清理参数，移除空值和无效值
    const params = {};
    Object.keys(searchObj.value).forEach(key => {
      if (searchObj.value[key] !== '' && searchObj.value[key] !== null && searchObj.value[key] !== undefined) {
        // 特别处理日期参数，确保格式正确
        if (key === 'bill_time') {
          // 如果是日期对象，转换为字符串格式
          if (searchObj.value[key] instanceof Date) {
            const date = searchObj.value[key];
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            params[key] = `${year}-${month}-${day} 00:00:00`;
          } else if (typeof searchObj.value[key] === 'string' && searchObj.value[key].match(/^\d{4}-\d{2}-\d{2}$/)) {
            // 如果是 YYYY-MM-DD 格式的字符串，补充时间部分
            params[key] = `${searchObj.value[key]} 00:00:00`;
          } else {
            // 其他情况直接使用
            params[key] = searchObj.value[key];
          }
        } else {
          // 确保数字类型参数是数字而不是字符串
          if (key === 'current' || key === 'limit' || key === 'staff.name' || key === 'room_fee' || key === 'extra_fee') {
            params[key] = Number(searchObj.value[key]);
          } else {
            params[key] = searchObj.value[key];
          }
        }
      }
    });

    console.log('实际发送的查询参数:', params);
    var result = await api.page(params);
    console.log('API返回结果:', result);
    if (result && result.data) {
      // 为每条账单数据添加员工姓名
      const billsWithStaffName = result.data.map(bill => {
        return {
          ...bill,
          staffName: staffMap.value[bill.staff_id] || '未知员工'
        };
      });

      tableData.value = billsWithStaffName;
      console.log("表格数据：", tableData.value);
      // 确保total是数字类型
      total.value = Number(result.count) || 0;
      console.log("总记录数：", total.value);
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("查询出错:", error);
    tableData.value = [];
    total.value = 0;
    ElMessage.error("查询数据失败");
  }
}

//页面加载后要挂载的数据
onMounted(async () => {
  await getCurrentUser();
  await loadStaffData();
  await search();
});

//定义方法
const handleSizeChange=()=>{
  search();
}

const handleCurrentChange=()=>{
  search();
}

const handlerSearch = () => {
  searchObj.value.current = 1;
  search();
}

const resetSearch = () => {
  searchObj.value = {
    current: 1,
    limit: 10,
    name: currentUser.value.id, // 保持当前用户ID
    room_fee: '',
    extra_fee: '',
    bill_time:''
  };
  search();
}
</script>

<style scoped>
.cyber-container {
  padding: 20px;
  min-height: calc(100vh - 40px);
  position: relative;
  overflow-y: auto;
}

.cyber-card {
  background: rgba(20, 20, 40, 0.7);
  border-radius: 12px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
  overflow: hidden;
  border: 1px solid rgba(0, 243, 255, 0.2);
  backdrop-filter: blur(5px);
  position: relative;
  margin-bottom: 20px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid rgba(0, 243, 255, 0.2);
  background: rgba(15, 15, 30, 0.8);
  flex-shrink: 0;
}

.card-header h2 {
  color: #00f3ff;
  font-size: 22px;
  margin: 0;
  text-shadow: 0 0 10px rgba(0, 243, 255, 0.5);
}

.cyber-form-card {
  padding: 20px;
  background: rgba(25, 25, 45, 0.6);
  margin: 20px;
  border-radius: 8px;
  border: 1px solid rgba(0, 243, 255, 0.1);
  flex-shrink: 0;
}

.cyber-table-card {
  padding: 0 20px 20px;
  flex: 1;
  overflow-y: auto;
}

.search-form .el-form-item {
  margin-bottom: 15px;
}

.search-form .el-input__wrapper {
  background: rgba(10, 10, 25, 0.5);
  border: 1px solid rgba(0, 243, 255, 0.3);
  box-shadow: 0 0 5px rgba(0, 243, 255, 0.2);
}

.search-form .el-input__wrapper.is-focus {
  box-shadow: 0 0 10px rgba(0, 243, 255, 0.4);
}

.form-actions {
  display: flex;
  justify-content: flex-start;
  gap: 15px;
  margin-top: 10px;
}

.cyber-button {
  background: rgba(50, 50, 80, 0.7);
  border: 1px solid rgba(0, 243, 255, 0.5);
  color: #00f3ff;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.cyber-button:hover {
  background: rgba(0, 243, 255, 0.2);
  box-shadow: 0 0 15px rgba(0, 243, 255, 0.4);
  border-color: #00f3ff;
}

.cyber-button.primary {
  background: linear-gradient(90deg, #00f3ff, #00aaff);
  border: 1px solid #00f3ff;
  color: #000;
  font-weight: 600;
}

.cyber-button.primary:hover {
  background: linear-gradient(90deg, #00aaff, #00f3ff);
  box-shadow: 0 0 20px rgba(0, 243, 255, 0.6);
}

.cyber-table-card :deep(.el-table) {
  background: rgba(20, 20, 40, 0.7);
  border: 1px solid rgba(0, 243, 255, 0.2);
  color: #e0e0ff;
}

.cyber-table-card :deep(.el-table__header th) {
  background: rgba(15, 15, 30, 0.9);
  color: #00f3ff;
  font-weight: 600;
}

.cyber-table-card :deep(.el-table__row:hover) {
  background: rgba(0, 243, 255, 0.1);
}

.cyber-table-card :deep(.el-table__row) {
  background: rgba(25, 25, 45, 0.5);
}

.cyber-table-card :deep(.el-table__cell) {
  border-color: rgba(0, 243, 255, 0.1);
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  flex-shrink: 0;
}

/* 固定定位的联系电话样式 */
.contact-info-fixed {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 10px 20px;
  background: rgba(0, 243, 255, 0.2);
  border: 1px solid rgba(0, 243, 255, 0.5);
  border-radius: 8px;
  color: #00f3ff;
  font-size: 16px;
  backdrop-filter: blur(5px);
  box-shadow: 0 0 10px rgba(0, 243, 255, 0.4);
  z-index: 1000;
}
</style>
